from datetime import datetime, timedelta
from tkinter import ttk, filedialog, messagebox

import tkinter as tk

from models.task_models import Task, TaskPriority
from notify.notification_manager import NotificationConfig, NotificationType
from notify.notification_sender import NotificationSender


class NotificationSettingsDialog(tk.Toplevel):
    """通知设置对话框"""

    def __init__(self, parent, db):
        super().__init__(parent)
        self.title("通知设置")
        self.geometry("600x500")
        self.transient(parent)
        self.grab_set()

        self.db = db
        self.config = NotificationConfig()

        # 主框架
        main_frame = ttk.Frame(self, padding=15)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 通知方式选择
        ttk.Label(main_frame, text="启用通知方式:", font=("Arial", 10, "bold")).pack(anchor=tk.W, pady=(0, 5))

        methods_frame = ttk.Frame(main_frame)
        methods_frame.pack(fill=tk.X, padx=5, pady=5)

        self.method_vars = {}
        for method in NotificationType:
            var = tk.BooleanVar(value=self.config.is_method_enabled(method))
            cb = ttk.Checkbutton(
                methods_frame,
                text=method.value,
                variable=var
            )
            cb.pack(anchor=tk.W, padx=5, pady=2)
            self.method_vars[method] = var

        # 分隔线
        ttk.Separator(main_frame, orient='horizontal').pack(fill=tk.X, pady=10)

        # 声音设置
        sound_frame = ttk.LabelFrame(main_frame, text="声音设置")
        sound_frame.pack(fill=tk.X, padx=5, pady=5)

        self.sound_enabled_var = tk.BooleanVar(
            value=self.config.get_setting("sound_settings", "enabled", False)
        )
        ttk.Checkbutton(
            sound_frame,
            text="启用声音提醒",
            variable=self.sound_enabled_var
        ).pack(anchor=tk.W, padx=5, pady=2)

        file_frame = ttk.Frame(sound_frame)
        file_frame.pack(fill=tk.X, padx=5, pady=5)

        ttk.Label(file_frame, text="声音文件:").pack(side=tk.LEFT)
        self.sound_file_var = tk.StringVar(
            value=self.config.get_setting("sound_settings", "file_path", "alarm.wav")
        )
        ttk.Entry(file_frame, textvariable=self.sound_file_var, width=30).pack(side=tk.LEFT, padx=5)
        ttk.Button(
            file_frame,
            text="浏览...",
            command=self.browse_sound_file,
            width=8
        ).pack(side=tk.LEFT)

        # 邮件设置
        email_frame = ttk.LabelFrame(main_frame, text="邮件通知设置")
        email_frame.pack(fill=tk.X, padx=5, pady=5)

        self.email_enabled_var = tk.BooleanVar(
            value=self.config.get_setting("email_settings", "enabled", False)
        )
        ttk.Checkbutton(
            email_frame,
            text="启用邮件通知",
            variable=self.email_enabled_var
        ).pack(anchor=tk.W, padx=5, pady=2)

        # ... 其他邮件设置字段（SMTP服务器、端口等）...

        # 自定义脚本设置
        script_frame = ttk.LabelFrame(main_frame, text="自定义脚本")
        script_frame.pack(fill=tk.X, padx=5, pady=5)

        # ... 自定义脚本设置字段 ...

        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        ttk.Button(
            btn_frame,
            text="测试通知",
            command=self.test_notification,
            width=10
        ).pack(side=tk.LEFT, padx=5)

        ttk.Button(
            btn_frame,
            text="保存",
            command=self.save_settings,
            style="Accent.TButton",
            width=10
        ).pack(side=tk.RIGHT, padx=5)

        ttk.Button(
            btn_frame,
            text="取消",
            command=self.destroy,
            width=10
        ).pack(side=tk.RIGHT, padx=5)

    def browse_sound_file(self):
        """浏览声音文件"""
        file_path = filedialog.askopenfilename(
            title="选择声音文件",
            filetypes=[("WAV文件", "*.wav"), ("所有文件", "*.*")]
        )
        if file_path:
            self.sound_file_var.set(file_path)

    def test_notification(self):
        """测试通知"""
        # 创建临时任务用于测试
        test_task = Task(
            title="测试任务",
            description="这是一个测试通知的任务",
            due_date=datetime.now().date() + timedelta(days=3),
            interval_days=1,
            priority=TaskPriority.HIGH
        )

        # 使用通知发送器发送测试通知
        notification_sender = NotificationSender(self.config, self.master.tray_icon, self.master)
        notification_sender.send("测试通知", "这是一个通知系统的测试消息", test_task)

    def save_settings(self):
        """保存设置"""
        # 更新启用的通知方式
        enabled_methods = []
        for method, var in self.method_vars.items():
            if var.get():
                enabled_methods.append(method.value)
        self.config.config["enabled_methods"] = enabled_methods

        # 更新声音设置
        self.config.update_setting("sound_settings", "enabled", self.sound_enabled_var.get())
        self.config.update_setting("sound_settings", "file_path", self.sound_file_var.get())

        # 更新邮件设置
        self.config.update_setting("email_settings", "enabled", self.email_enabled_var.get())

        # 保存所有设置
        self.config.save_config()
        messagebox.showinfo("成功", "通知设置已保存")
        self.destroy()
